var AjaxLink = function(link) {
	
	var $this = this;
	this.link = link;
	var currentRequest;
	
	this.startAjaxRequest = function(url, type, params, onend) {
		if (currentRequest) {
			currentRequest.stop();
		}
		currentRequest = new Request(url, type, params);
		currentRequest.onload = onend;
		currentRequest.start();
	};
	this.onEndRequest = function(e) {
		var elem = JSD.$($this.link.getAttribute("target"));

		if (elem) {
			elem.JSD().setInnerHTML(currentRequest.getResponseText());
			AjaxLink.init(elem);
		}
		currentRequest = null;
	};
	
	this.onclickLink = function() {
		var target = this.getAttribute("target");
		var url = this.getAttribute("href");
		
		$this.startAjaxRequest(url, "GET", {}, $this.onEndRequest);
	};
	this.init = function() {
		JSD.on("click", ".ajaxlink", $this.onclickLink);
	};
	
	function __construct(link) {
		JSD.on("click", link, $this.onclickLink);
	}
	
	__construct(link);
};

AjaxLink.init = function(elem) {
	var links;
	if (!elem) {
		links = JSD.$$(".ajaxlink");
	} else {
		var elem = JSD.$(elem);
		links = elem.JSD().getElemsByCSSRule(".ajaxlink");
	}
	for (var i = 0; i < links.length; i++) {
		var al = new AjaxLink(links[i]);
	}
};

JSD.onready(function() { AjaxLink.init(); });